package com.yy.servlet;

import com.yy.db.StudentDBUtil;
import com.yy.pojo.Student;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet(name="GetStudentsServlet",value = "/getStudents")
public class GetStudentsServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取所有学生信息
        StudentDBUtil studentDBUtil=new StudentDBUtil();
        String sname = req.getParameter("sname");
        String pageNum = req.getParameter("pageNum");


        Integer pageSize=3;
        //首次初始化页面，没有pageNum ，设置为1
        if(pageNum==null||"".equals(pageNum)){
            pageNum="1";
        }
        int pageNumInt=Integer.parseInt(pageNum);
        //根据每页显示条数 计算总页数
        int totalPages=studentDBUtil.getTotalPages(pageSize);
        System.out.println(totalPages);
        if(pageNumInt>totalPages){
            pageNumInt=totalPages;
        }
        if(pageNumInt<1){
            pageNumInt=1;
        }
        List<Student> stus;

        if(sname==null||"".equals(sname)){

            req.getSession().setAttribute("pageNum", pageNumInt);
            req.getSession().setAttribute("totalPages", totalPages);
            stus=studentDBUtil.getAllStusByPage(pageNumInt, pageSize);

        }else{
            stus=studentDBUtil.getAllStusBySname(sname);
//            stus=studentDBUtil.getStuByPageAndSname(pageNumInt,pageSize,sname);
        }
        req.getSession().setAttribute("stus", stus);
        resp.sendRedirect("/studentsList.jsp");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
      doGet(req,resp);
    }
}
